<template>
  <Layout>
    <div class="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <!-- 标题和操作栏 -->
      <div class="bg-white rounded-lg shadow-md overflow-hidden">
        <div class="px-6 py-4 border-b">
          <div class="flex justify-between items-center">
            <h1 class="text-2xl font-bold text-gray-900">通知中心</h1>
            <div class="flex items-center space-x-4">
              <span class="text-sm text-gray-500">
                {{ unreadCount }} 条未读
              </span>
              <div class="flex space-x-2">
                <button
                  @click="markAllAsRead"
                  v-if="unreadCount > 0"
                  class="px-3 py-1 text-sm bg-blue-600 text-white rounded-md hover:bg-blue-700"
                >
                  全部标记已读
                </button>
                <button
                  @click="clearAll"
                  v-if="notifications.length > 0"
                  class="px-3 py-1 text-sm bg-gray-200 text-gray-700 rounded-md hover:bg-gray-300"
                >
                  清空通知
                </button>
              </div>
            </div>
          </div>
        </div>

        <!-- 筛选标签 -->
        <div class="px-6 py-3 border-b bg-gray-50">
          <div class="flex space-x-4">
            <button
              @click="currentFilter = 'all'"
              :class="currentFilter === 'all' ? 'text-blue-600 border-b-2 border-blue-600' : 'text-gray-600 hover:text-gray-900'"
              class="pb-1 text-sm font-medium"
            >
              全部
            </button>
            <button
              @click="currentFilter = 'unread'"
              :class="currentFilter === 'unread' ? 'text-blue-600 border-b-2 border-blue-600' : 'text-gray-600 hover:text-gray-900'"
              class="pb-1 text-sm font-medium"
            >
              未读
            </button>
            <button
              @click="currentFilter = 'comment'"
              :class="currentFilter === 'comment' ? 'text-blue-600 border-b-2 border-blue-600' : 'text-gray-600 hover:text-gray-900'"
              class="pb-1 text-sm font-medium"
            >
              评论
            </button>
            <button
              @click="currentFilter = 'like'"
              :class="currentFilter === 'like' ? 'text-blue-600 border-b-2 border-blue-600' : 'text-gray-600 hover:text-gray-900'"
              class="pb-1 text-sm font-medium"
            >
              点赞
            </button>
            <button
              @click="currentFilter = 'follow'"
              :class="currentFilter === 'follow' ? 'text-blue-600 border-b-2 border-blue-600' : 'text-gray-600 hover:text-gray-900'"
              class="pb-1 text-sm font-medium"
            >
              关注
            </button>
            <button
              @click="currentFilter = 'system'"
              :class="currentFilter === 'system' ? 'text-blue-600 border-b-2 border-blue-600' : 'text-gray-600 hover:text-gray-900'"
              class="pb-1 text-sm font-medium"
            >
              系统
            </button>
          </div>
        </div>

        <!-- 通知列表 -->
        <div>
          <div v-if="loading" class="py-12 text-center">
            <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
            <p class="mt-2 text-gray-500">加载中...</p>
          </div>

          <div v-else-if="filteredNotifications.length === 0" class="py-12 text-center">
            <svg class="mx-auto h-12 w-12 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9" />
            </svg>
            <p class="mt-2 text-gray-500">暂无通知</p>
          </div>

          <div v-else class="divide-y divide-gray-200">
            <div
              v-for="notification in filteredNotifications"
              :key="notification.id"
              :class="[
                'px-6 py-4 hover:bg-gray-50 transition-colors cursor-pointer',
                !notification.is_read && 'bg-blue-50'
              ]"
              @click="handleNotificationClick(notification)"
            >
              <div class="flex items-start">
                <!-- 图标 -->
                <div class="flex-shrink-0">
                  <div
                    :class="[
                      'w-10 h-10 rounded-full flex items-center justify-center',
                      getNotificationColor(notification.type)
                    ]"
                  >
                    <component :is="getNotificationIcon(notification.type)" class="w-5 h-5 text-white" />
                  </div>
                </div>

                <!-- 内容 -->
                <div class="ml-4 flex-1">
                  <div class="flex items-start justify-between">
                    <div class="flex-1">
                      <p class="text-sm font-medium text-gray-900">
                        {{ notification.title }}
                      </p>
                      <p class="mt-1 text-sm text-gray-600">
                        {{ notification.content }}
                      </p>
                      <p class="mt-1 text-xs text-gray-500">
                        {{ formatTime(notification.created_at) }}
                      </p>
                    </div>

                    <!-- 操作按钮 -->
                    <div class="ml-4 flex items-center space-x-2">
                      <button
                        v-if="!notification.is_read"
                        @click.stop="markAsRead(notification)"
                        class="text-blue-600 hover:text-blue-800"
                        title="标记为已读"
                      >
                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                        </svg>
                      </button>
                      <button
                        @click.stop="deleteNotification(notification)"
                        class="text-gray-400 hover:text-red-600"
                        title="删除"
                      >
                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                        </svg>
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 分页 -->
          <div v-if="totalPages > 1" class="px-6 py-4 border-t">
            <div class="flex justify-center">
              <nav class="flex space-x-2">
                <button
                  @click="currentPage--"
                  :disabled="currentPage === 1"
                  class="px-3 py-1 rounded-md border border-gray-300 text-sm text-gray-700 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  上一页
                </button>
                <button
                  v-for="page in visiblePages"
                  :key="page"
                  @click="currentPage = page"
                  :class="currentPage === page ? 'bg-blue-600 text-white' : 'border border-gray-300 text-gray-700 hover:bg-gray-50'"
                  class="px-3 py-1 rounded-md text-sm"
                >
                  {{ page }}
                </button>
                <button
                  @click="currentPage++"
                  :disabled="currentPage === totalPages"
                  class="px-3 py-1 rounded-md border border-gray-300 text-sm text-gray-700 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  下一页
                </button>
              </nav>
            </div>
          </div>
        </div>
      </div>
    </div>
  </Layout>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { router } from '@inertiajs/inertia-vue3'
import Layout from '@/Components/Layout.vue'
import axios from 'axios'

const loading = ref(false)
const notifications = ref([])
const unreadCount = ref(0)
const currentFilter = ref('all')
const currentPage = ref(1)
const perPage = 20
const total = ref(0)

// 筛选后的通知
const filteredNotifications = computed(() => {
  let filtered = notifications.value

  if (currentFilter.value === 'unread') {
    filtered = filtered.filter(n => !n.is_read)
  } else if (currentFilter.value !== 'all') {
    filtered = filtered.filter(n => n.type === currentFilter.value)
  }

  return filtered
})

// 总页数
const totalPages = computed(() => {
  return Math.ceil(total.value / perPage)
})

// 可见页码
const visiblePages = computed(() => {
  const pages = []
  const start = Math.max(1, currentPage.value - 2)
  const end = Math.min(totalPages.value, currentPage.value + 2)

  for (let i = start; i <= end; i++) {
    pages.push(i)
  }

  return pages
})

// 获取通知图标
const getNotificationIcon = (type) => {
  const icons = {
    follow: 'UserPlusIcon',
    comment: 'ChatIcon',
    like: 'HeartIcon',
    favorite: 'BookmarkIcon',
    system: 'BellIcon',
    post_approved: 'CheckCircleIcon',
    post_rejected: 'XCircleIcon',
  }
  return icons[type] || 'BellIcon'
}

// 获取通知颜色
const getNotificationColor = (type) => {
  const colors = {
    follow: 'bg-blue-500',
    comment: 'bg-green-500',
    like: 'bg-red-500',
    favorite: 'bg-yellow-500',
    system: 'bg-gray-500',
    post_approved: 'bg-green-600',
    post_rejected: 'bg-red-600',
  }
  return colors[type] || 'bg-gray-500'
}

// 格式化时间
const formatTime = (time) => {
  const date = new Date(time)
  const now = new Date()
  const diff = now - date

  if (diff < 60000) {
    return '刚刚'
  } else if (diff < 3600000) {
    return Math.floor(diff / 60000) + '分钟前'
  } else if (diff < 86400000) {
    return Math.floor(diff / 3600000) + '小时前'
  } else if (diff < 2592000000) {
    return Math.floor(diff / 86400000) + '天前'
  } else {
    return date.toLocaleDateString()
  }
}

// 加载通知
const loadNotifications = async () => {
  loading.value = true
  try {
    const response = await axios.get('/api/notifications', {
      params: {
        page: currentPage.value,
        per_page: perPage,
        type: currentFilter.value !== 'all' && currentFilter.value !== 'unread' ? currentFilter.value : null,
        is_read: currentFilter.value === 'unread' ? false : null,
      }
    })

    notifications.value = response.data.notifications
    unreadCount.value = response.data.unread_count
    total.value = response.data.pagination.total
  } catch (error) {
    console.error('加载通知失败:', error)
  } finally {
    loading.value = false
  }
}

// 标记为已读
const markAsRead = async (notification) => {
  try {
    await axios.post(`/api/notifications/${notification.id}/mark-as-read`)
    notification.is_read = true
    notification.read_at = new Date()
    unreadCount.value--
  } catch (error) {
    console.error('标记失败:', error)
  }
}

// 标记全部已读
const markAllAsRead = async () => {
  try {
    await axios.post('/api/notifications/mark-all-as-read')
    notifications.value.forEach(n => {
      if (!n.is_read) {
        n.is_read = true
        n.read_at = new Date()
      }
    })
    unreadCount.value = 0
  } catch (error) {
    console.error('标记失败:', error)
  }
}

// 删除通知
const deleteNotification = async (notification) => {
  if (!confirm('确定要删除这条通知吗？')) return

  try {
    await axios.delete(`/api/notifications/${notification.id}`)
    const index = notifications.value.findIndex(n => n.id === notification.id)
    if (index > -1) {
      if (!notification.is_read) {
        unreadCount.value--
      }
      notifications.value.splice(index, 1)
    }
  } catch (error) {
    console.error('删除失败:', error)
  }
}

// 清空通知
const clearAll = async () => {
  if (!confirm('确定要清空所有通知吗？')) return

  try {
    await axios.post('/api/notifications/clear')
    notifications.value = []
    unreadCount.value = 0
  } catch (error) {
    console.error('清空失败:', error)
  }
}

// 点击通知
const handleNotificationClick = async (notification) => {
  // 先标记为已读
  if (!notification.is_read) {
    await markAsRead(notification)
  }

  // 根据通知类型跳转
  if (notification.data?.post_slug) {
    router.visit(`/posts/${notification.data.post_slug}`)
  } else if (notification.data?.user_username) {
    router.visit(`/profile/${notification.data.user_username}`)
  }
}

onMounted(() => {
  loadNotifications()
})
</script>